/**
 * Created by mango on 2017/3/1.
 */
let path = require('path');
let fs = require('fs');
let assetsInfo = require('./../assets');
let bulid = require('./../bulid');
let summary = require('./summary');
let content = require('./content')
module.exports = {

    run: function () {


        //获取文件夹


        //读取文件
        var tree = this.getDirTree();
        //写入文件


        summary.create(tree);


    },
    newFile: function (fileName, title, filePath, filePathFull) {
        return {
            fileName: fileName,
            title: title,
            filePath: filePath,
            filePathFull: filePathFull,
            type: "file"
        }
    },
    newDir: function (tile, path, pathFull) {
        return {
            title: tile,
            path: path,
            filePath: path,
            pathFull: pathFull,
            fileName: 'index',
            type: "dir",
            files: []
        }
    },
    getDirTree: function () {

        var entity = [];
        var jsonPath = path.join(assetsInfo.dirName, 'json');

        this.readDir(jsonPath, '', entity);
        return entity;
    },
    readDir: function (parentPathFull, parentPath, entity) {


        var indexPath = path.join(parentPathFull, 'index.json'); //确定该文件为 document 需要解析文件夹
        if (fs.existsSync(indexPath)) {

            var stream = fs.readFileSync(indexPath, 'utf-8');

            var json = JSON.parse(stream);

            var dir = this.newDir(json.title, parentPath, parentPathFull)

            content.createFile(bulid.dirName, dir);
            this.readFile(parentPathFull, parentPath, dir.files);
            entity.push(dir);
            //todo 创建文件夹


        } else {
            //json 为一级菜单
            this.readFile(parentPathFull, parentPath, entity);
        }
    },
    readFile: function (parentPathFull, parentPath, entity) {
        var _this = this;
        var jsonFiles = fs.readdirSync(parentPathFull, {encoding: 'utf8'});
        jsonFiles.forEach((fileName) => {
            if (fileName !== 'index.json') {
                var currentPath = path.join(parentPathFull, fileName);
                var stats = fs.statSync(currentPath);
                if (stats.isFile()) {
                    var stream = fs.readFileSync(currentPath, 'utf-8');
                    var json = JSON.parse(stream);
                    var file = _this.newFile(fileName.split('.')[0], json.title, parentPath, currentPath);
                    entity.push(file);
                    //todo 形成 md 文件
                    content.createFile(bulid.dirName, file, json);
                }
                if (stats.isDirectory()) {
                    _this.readDir(currentPath, parentPath + fileName + '/', entity);
                }
            }
        });
    }
}